/**
 * @author: 子龙
 */
package com.fzl.lotterysystem.common.utils;


import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class SMSUtil {
    private static final Logger logger = LoggerFactory.getLogger(SMSUtil.class);

    @Value(value = "${sms.sign-name}")
    private String signName;

    @Value(value = "${sms.access-key-id}")
    private String accessKeyId;

    @Value(value = "${sms.access-key-secret}")
    private String accessKeySecret;

    @Value(value = "${sms.sdk-app-id}")
    private String sdkAppId;

    @Value(value = "${sms.region-id:ap-guangzhou}")
    private String regionId;

    /**
     * 发送短信
     *
     * @param templateCode 模板号
     * @param phoneNumbers 手机号
     * @param templateParam 模板参数 {"key":"value"}
     */
    public void sendMessage(String templateCode, String phoneNumbers, String templateParam) {
        try {
            // 创建短信客户端
            SmsClient client = createClient();

            // 构建发送请求
            SendSmsRequest request = new SendSmsRequest();
            // 设置手机号（腾讯云要求格式为+8613800138000）
            String[] phoneNumberSet = phoneNumbers.split(",");
            for (int i = 0; i < phoneNumberSet.length; i++) {
                if (!phoneNumberSet[i].startsWith("+86")) {
                    phoneNumberSet[i] = "+86" + phoneNumberSet[i];
                }
            }
            request.setPhoneNumberSet(phoneNumberSet);
            request.setSignName(signName);
            request.setTemplateId(templateCode);
            request.setSmsSdkAppId(sdkAppId);

            // 解析模板参数（腾讯云要求为数组格式）
            // 注意：这里需要根据实际模板参数格式进行调整
            String[] params = parseTemplateParam(templateParam);
            request.setTemplateParamSet(params);

            // 发送短信
            SendSmsResponse response = client.SendSms(request);

            // 处理响应结果
            if (response != null && "Ok".equals(response.getSendStatusSet()[0].getCode())) {
                logger.info("向{}发送信息成功，templateCode={}", phoneNumbers, templateCode);
                return;
            }

            // 失败处理
            String errorMsg = response != null && response.getSendStatusSet() != null
                    ? response.getSendStatusSet()[0].getMessage()
                    : "未知错误";
            logger.error("向{}发送信息失败，templateCode={}，失败原因：{}",
                    phoneNumbers, templateCode, errorMsg);

        } catch (TencentCloudSDKException e) {
            logger.error("向{}发送信息失败，templateCode={}", phoneNumbers, templateCode, e);
        } catch (Exception e) {
            logger.error("向{}发送信息失败，templateCode={}", phoneNumbers, templateCode, e);
        }
    }

    /**
     * 解析模板参数为腾讯云要求的数组格式
     */
    private String[] parseTemplateParam(String templateParam) {
        // 简单处理：去除{}并按逗号分割（实际项目中建议使用JSON解析）
        if (templateParam == null || templateParam.isEmpty()) {
            return new String[0];
        }
        String paramStr = templateParam.replaceAll("[{}\"']", "");
        return paramStr.split(",");
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return SmsClient
     */
    private SmsClient createClient() {
        // 实例化认证对象
        Credential cred = new Credential(accessKeyId, accessKeySecret);

        // 配置HTTP选项
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        httpProfile.setConnTimeout(30);

        // 配置客户端选项
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化短信客户端
        return new SmsClient(cred, regionId, clientProfile);
    }
}
